<?php
class Model_Core_Resource_Abstract
    extends Zend_Db_Table_Abstract
{
    protected $_name;

    protected $_primary;

    protected function _init($tableName,$primary)
    {
        if(!isset($tableName) || !isset($primary)) {
            throw new Zend_Exception('Not set init parametrs in resource model '.get_class($this));
        }

        $this->_name = $tableName;
        $this->_primary = $primary;

        return $this;
    }

    public function load(&$model, $value, $field=null)
    {
        $select = $this->getAdapter()->select()
                        ->from($this->_name);
        if($field) {
            $select->where($this->formatFieldToWhere($field),$value);
        } else {
            $select->where($this->formatFieldToWhere($this->_primary),$value);
        }
        $select->limit(1);
        $result = $this->getAdapter()->query($select);

        $result = $result->fetchAll(Zend_Db::FETCH_OBJ);

        $model->setPrimary($this->_primary);
        if(isset($result[0])) {
            $model->setOriginalData((array)$result[0]);
        }

        return $this;
    }

    protected function formatFieldToWhere($field)
    {
        return $this->_name.'.'.$field.' = ?';
    }

    public function save(&$model)
    {
        if($model->getIsDataChange()) {
            $data = $model->getData();

            $fields = $this->getAdapter()->describeTable($this->_name);
            foreach ($data as $key=>$value) {
                if(!array_key_exists($key, $fields)) {
                    unset($data[$key]);
                }
            }

            if(!$model->getIsNew()) {
                $where = $this->getAdapter()->quoteInto($this->_primary.' = ?', $model->getId());
                $this->update($data, $where);
            } else {
                $this->insert($data);
                $model->setIsNew(false);
                $insertId = $this->getAdapter()->lastInsertId($this->_name);
                $model->setId($insertId);
            }

            $model->getIsDataChange(false);
        }

        return $this;
    }

    public function deleteModel(&$model)
    {
        if(!$model->getIsNew()) {
            $where = $this->getAdapter()->quoteInto($this->_primary.' = ?', $model->getId());
            $this->delete($where);
        }

        $model->setOriginalData(array());
        $model->setIsNew(true);
        $model->setIsDataChange(false);

        return $this;
    }
}